package com.oocl.euc.core.maintenance.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.euc.core.builder.UsersBuilder;
import com.oocl.euc.core.common.ITTestBase;
import com.oocl.euc.core.maintenance.model.Users;
import com.oocl.euc.core.maintenance.repository.UsersRepository;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import static org.hamcrest.core.Is.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

public class UsersControllerIT extends ITTestBase {

    @Autowired
    UsersBuilder usersBuilder;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    UsersRepository usersRepository;

    private Users users1;
    private Users users2;

    @After
    public void reset() {
    }

    @Test
    public void should_return_two_departments_when_given_two_users() throws Exception {
        users1 = usersBuilder.defaultBuilder()
                .withStaffId("TEST1")
                .withDepartment("TEST1")
                .withNeedSync(false)
                .saveToDB();

        users2 = usersBuilder.defaultBuilder()
                .withStaffId("TEST2")
                .withDepartment("TEST2")
                .withNeedSync(false)
                .saveToDB();
        mockMvc.perform(get("/rest/users/getDepartments").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$", Matchers.hasSize(2)))
                .andExpect(jsonPath("$[0]", is(users2.getDepartment())))
                .andExpect(jsonPath("$[1]", is(users1.getDepartment())));
        usersRepository.delete(users1);
        usersRepository.delete(users2);
    }

    @Test
    public void should_return_user_with_need_sync_equal_false_when_given_two_users() throws Exception {
        users1 = usersBuilder.defaultBuilder()
                .withStaffId("TEST1")
                .withDepartment("TEST1")
                .create();
        String requestJson = objectMapper.writeValueAsString(users1);

        mockMvc.perform(post("/rest/users/saveTempUser")
                .content(requestJson).contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.needSync").value(false));
        usersRepository.delete(users1);
    }
}
